<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="100px" @submit.prevent>
      <el-form-item label="储位编码" prop="locationCode">
        <el-input
          v-model.trim="queryParams.locationCode"
          placeholder="请输入储位编码"
          clearable
          @keyup.enter="handleQuery"
          style="width: 175px"
        />
      </el-form-item>
      <el-form-item label="货架类型" prop="shelfType">
        <el-select
          v-model="queryParams.shelfType"
          placeholder="请选择货架类型"
          clearable
          style="width: 175px"
          @change="handleQuery"
        >
          <el-option
            v-for="item in shelfTypeList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="货架编号" prop="shelfId">
        <el-input
          v-model.trim="queryParams.shelfId"
          placeholder="请输入货架编号"
          clearable
          @keyup.enter="handleQuery"
          style="width: 175px"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:location:add']"
        >新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:location:edit']"
        >修改</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:location:remove']"
        >批量删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['system:location:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Download"
          @click="downloadTemplate"
        >下载导入模板</el-button>
      </el-col>
      <el-col :span="1.5">
        <MyUpload
          buttonName="导入货架储位" 
          url="/api/return/location/import"
          @success="handleUploadSuccess"
          @warning="handleUploadWarning"
          />
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <TableScrollContainer :topHeight="220">
      <template #default="{ tableHeight }">
        <el-table v-loading="loading" :data="locationList" @selection-change="handleSelectionChange" :height="tableHeight" border>
          <el-table-column type="selection" width="55" align="center" />
          <!-- <el-table-column label="主键ID" align="center" prop="id" /> -->
          <el-table-column label="储位编码" align="center" prop="locationCode" />
          <el-table-column label="货架类型" align="center" prop="shelfType">
            <template #default="scope">
              <!-- <div v-if="scope.row.shelfType === 'NORMAL'">普通货架</div>
              <div v-else>亮灯货架</div> -->
              {{ scope.row.shelfType }}
            </template>
          </el-table-column>
          <el-table-column label="货架编号" align="center" prop="shelfId" />
          <el-table-column label="区域类型" align="center" prop="areaType">
            <template #default="scope">
              <dict-tag :options="area_type" :value="scope.row.areaType"></dict-tag>
            </template>
          </el-table-column>
          <el-table-column label="层数" align="center" prop="layerNum" />
          <el-table-column label="面数" align="center" prop="sideType">
            <template #default="scope">
              <dict-tag :options="side_count" :value="scope.row.sideType"></dict-tag>
            </template>
          </el-table-column>
          <el-table-column label="容纳料盘数" align="center" prop="capacity" />
          <el-table-column label="适配料盘尺寸" align="center" prop="diskSize" />
          <el-table-column label="最大厚度(mm)" align="center" prop="maxThickness" />
          <el-table-column label="储位状态" align="center" prop="locationStatus">
            <template #default="scope">
              <dict-tag :options="take_status" :value="scope.row.locationStatus"></dict-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="190" fixed="right">
            <template #default="scope">
              <el-button type="success" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:location:edit']">修改</el-button>
              <el-button type="danger" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:location:remove']">删除</el-button>
            </template>
          </el-table-column>  
        </el-table>
        <pagination
          v-show="total>0"
          :total="total"
          :page-sizes="[10, 30, 50, 100]"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
        />
      </template>
    </TableScrollContainer>

    <!-- 添加或修改退料区储位对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" :close-on-click-modal="false">
      <el-form ref="locationRef" :model="form" :rules="rules" label-width="120px">
        <!-- <el-form-item label="储位编码" prop="locationCode">
          <el-input v-model="form.locationCode" placeholder="请输入储位编码" />
        </el-form-item> -->
        <el-form-item label="货架类型" prop="shelfType">
          <el-select v-model="form.shelfType" placeholder="请选择货架类型">
            <el-option
              v-for="item in shelfTypeList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="货架编号" prop="shelfId">
          <el-input v-model="form.shelfId" placeholder="请输入货架编号" />
        </el-form-item>
        <el-form-item label="区域类型" prop="areaType">
          <el-select v-model="form.areaType" placeholder="请选择区域类型">
            <el-option
              v-for="item in area_type"
              :key="item.value"
              :label="item.label"
              :value="Number(item.value)"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="层数" prop="layerNum">
          <el-input @input="handleNumberInput('layerNum')" v-model.number="form.layerNum" placeholder="请输入层数" />
        </el-form-item>
        <el-form-item label="面数" prop="sideType">
          <el-select v-model="form.sideType" placeholder="请选择面数">
            <el-option
              v-for="item in side_count"
              :key="item.value"
              :label="item.label"
              :value="Number(item.value)"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="容纳料盘数" prop="capacity">
          <el-input v-model="form.capacity" placeholder="请输入容纳料盘数" />
        </el-form-item>
        <el-form-item label="适配料盘尺寸" prop="diskSize">
          <el-input v-model="form.diskSize" placeholder="请输入适配料盘尺寸" />
           <!-- <el-select v-model="form.diskSize" placeholder="请选择料盘尺寸(mm)">
             <el-option
               v-for="item in diskSizeList"
               :key="item.value"
               :label="item.label"
               :value="item.value"
             />
           </el-select> -->
        </el-form-item>
        <el-form-item label="最大厚度(mm)" prop="maxThickness">
          <el-input v-model="form.maxThickness" placeholder="请输入最大厚度(mm)" />
        </el-form-item>
        <el-form-item label="储位状态" prop="locationStatus">
          <el-select v-model="form.locationStatus" placeholder="请选择储位状态">
            <el-option
              v-for="item in take_status"
              :key="item.value"
              :label="item.label"
              :value="parseInt(item.value)"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="backStorage">
import { listLocation, getLocation, delLocation, addLocation, updateLocation } from "@/api/work/backStorage"
import TableScrollContainer from '@/components/Pagetable/TableScrollContainer.vue'

const { proxy } = getCurrentInstance()
const { side_count, area_type, take_status } = proxy.useDict('side_count', 'area_type', 'take_status')

const shelfTypeList = ref([{
  value: 'SS-7D1008',
  label: 'SS-7D1008'
},{
  value: 'SS-4D448',
  label: 'SS-4D448'
},{
  value: 'SS-4D192',
  label: 'SS-4D192'
},{
  value: '普通货架',
  label: '普通货架'
}])
const diskSizeList = ref([{
  value: '7寸',
  label: '7寸'
}, {
  value: '13寸',
  label: '13寸'
}, {
  value: '其他尺寸',
  label: '其他尺寸'
}])
const locationList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    locationCode: null,
    shelfId: null,
    shelfType: null
  },
  rules: {
    shelfType: [
      { required: true, message: '请选择货架类型', trigger: 'blur' }
    ],
    shelfId: [
      { required: true, message: '请输入货架编号', trigger: 'blur' }
    ],
    areaType: [
      { required: true, message: '请选择区域类型', trigger: 'blur' }
    ],
    layerNum: [
      { required: true, message: '请输入层数', trigger: 'blur' },
      { 
        validator: (rule, value, callback) => {
          if (value < 1) {
            callback(new Error('请输入大于0数值'));
          } else {
            callback();
          }
        },
        trigger: 'blur'
      }
    ],
    sideType: [
      { required: true, message: '请选择面数', trigger: 'blur' }
    ],
    capacity: [
      { required: true, message: '请输入容纳料盘数', trigger: 'blur' }
    ],
    diskSize: [
      { required: true, message: '请输入适配料盘尺寸', trigger: 'blur' }
    ],
    maxThickness: [
      { required: true, message: '请输入最大厚度(mm)', trigger: 'blur' }
    ] 
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询退料区储位列表 */
function getList() {
  loading.value = true
  listLocation(queryParams.value).then(res => {
    if (res.errCode === '1') {
      locationList.value = res.data.page.records
      total.value = res.data.page.total
      loading.value = false
    }
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    returnAreaId: null,
    locationCode: null,
    shelfId: null,
    shelfType: null,
    areaType: null,
    layerNum: null,
    sideType: null,
    capacity: null,
    diskSize: null,
    maxThickness: null,
    locationStatus: null,
    createTime: null,
    updateTime: null
  }
  proxy.resetForm("locationRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.returnAreaId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加退料区储位"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.returnAreaId || ids.value
  getLocation(_id).then(res => {
    form.value = res.data.location
    open.value = true
    title.value = "修改退料区储位"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["locationRef"].validate(valid => {
    if (valid) {
      if (form.value.returnAreaId != null) {
        updateLocation(form.value).then(res => {
          if (res.errCode === '1') {
            proxy.$modal.msgSuccess("修改成功")
            open.value = false
            getList()
          } else {
            proxy.$modal.msgError(res.msg)
          }
        })
      } else {
        addLocation(form.value).then(res => {
          if (res.errCode === '1') {
            proxy.$modal.msgSuccess("新增成功")
            open.value = false
            getList()
          } else {
            proxy.$modal.msgError(res.msg)
          }
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.returnAreaId || ids.value
  proxy.$modal.confirm('是否确认删除退料区储位编号为"' + _ids + '"的数据项？').then(function() {
    return delLocation(_ids)
  }).then(res => {
    if (res.errCode === '1') {
      getList()
      proxy.$modal.msgSuccess("删除成功")
    } else {
      proxy.$modal.msgError(res.msg)
    }
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('api/return/location/export', {
    ...queryParams.value
  }, `退料区储位数据_${new Date().getTime()}.xlsx`)
}

getList()

// 下载模板
const downloadTemplate = async() => {
  proxy.download('/api/return/location/downloadTemplate', {}, `退料区储位模板_${new Date().getTime()}.xlsx`)
}
// 上传成功后的回调
const handleUploadSuccess = (res) => {
  getList()
}
// 部分成功回调
const handleUploadWarning = (res) => {
  getList()
}

const handleNumberInput = (key) => {
  form.value[key] = form.value[key]
    .toString()
    .replace(/[^\d.]/g, '')
    .replace(/\.{2,}/g, '.')
    .replace(/^\./, '')
}
</script>